package net.starwifi.duobao.web.shop;

import net.starwifi.duobao.entity.*;
import net.starwifi.duobao.mvc.BaseController;
import net.starwifi.duobao.mvc.Message;
import net.starwifi.duobao.service.*;
import net.starwifi.duobao.utils.WebUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by Administrator on 2015/11/9.
 */
@Controller("shopCartController")
@RequestMapping(value = "/shop/cart")
public class CartController extends BaseController {


    @Autowired
    ProductService productService;

    @Autowired
    CartService cartService;

    @Autowired
    CartItemService cartItemService;

    @Autowired
    MemberService memberService;

    @Autowired
    OrderService orderService;

    @Autowired
    PaymentMethodService paymentMethodService;

    @Autowired
    ReceiverService receiverService;

    /**
     * 购物车
     */
    @ResponseBody
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Object add(Long id, HttpServletRequest request, HttpServletResponse response) {
        int quantity=1;
        Product product = productService.find(id);
        if (product == null) {
            return Message.warn("产品不存在");
        }
        if (!product.getIsMarketable()) {
            return Message.warn("产品未上架");
        }
        if (product.getIsGift()) {
            return Message.warn("赠品不能购买");
        }

        Cart cart = cartService.getCurrent();
        Member member = memberService.getCurrent();

        if (cart == null) {
            cart = new Cart();
            cart.setKey(UUID.randomUUID().toString() + DigestUtils.md5Hex(RandomStringUtils.randomAlphabetic(30)));
            cart.setMember(member);
            cartService.save(cart);
        }

        if (Cart.MAX_PRODUCT_COUNT != null && cart.getCartItems().size() >= Cart.MAX_PRODUCT_COUNT) {
            return Message.warn("达到购物车上限", Cart.MAX_PRODUCT_COUNT);
        }
        if (cart.contains(product)) {
            CartItem cartItem = cart.getCartItem(product);
            if (CartItem.MAX_QUANTITY != null && cartItem.getQuantity() + quantity > CartItem.MAX_QUANTITY) {
                return Message.warn("达到单品购买上限", CartItem.MAX_QUANTITY);
            }
            if (product.getStock() != null && cartItem.getQuantity() + quantity > product.getAvailableStock()) {
                return Message.warn("库存不足");
            }
            cartItem.add(quantity);
            cartItemService.update(cartItem);
        } else {
            if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
                return Message.warn("达到单品购买上限", CartItem.MAX_QUANTITY);
            }
            if (product.getStock() != null && quantity > product.getAvailableStock()) {
                return Message.warn("达到单品购买上限");
            }
            CartItem cartItem = new CartItem();
            cartItem.setQuantity(quantity);
            cartItem.setProduct(product);
            cartItem.setCart(cart);
            cartItemService.save(cartItem);
            cart.getCartItems().add(cartItem);
        }
        if (member == null) {
            WebUtils.addCookie(request, response, Cart.ID_COOKIE_NAME, cart.getId().toString(), Cart.TIMEOUT);
            WebUtils.addCookie(request, response, Cart.KEY_COOKIE_NAME, cart.getKey(), Cart.TIMEOUT);
        }
        return Message.success("添加成功", cart.getQuantity(), cart.getPrice(), true, false);
    }


    /**
     * 编辑
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> edit(Long id, Integer quantity) {
        Map<String, Object> data = new HashMap<String, Object>();
        if (quantity == null || quantity < 1) {
            data.put("message", ERROR_MESSAGE);
            return data;
        }
        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            data.put("message", Message.error("购物车不能为空"));
            return data;
        }
        CartItem cartItem = cartItemService.find(id);
        Set<CartItem> cartItems = cart.getCartItems();
        if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
            data.put("message", Message.error("购物车无该商品"));
            return data;
        }
        if (CartItem.MAX_QUANTITY != null && quantity > CartItem.MAX_QUANTITY) {
            data.put("message", Message.warn("已达到单项商品数量限制", CartItem.MAX_QUANTITY));
            return data;
        }
        Product product = cartItem.getProduct();
        if (product.getStock() != null && quantity > product.getAvailableStock()) {
            data.put("message", Message.warn("产品库存不足"));
            return data;
        }
        cartItem.setQuantity(quantity);
        cartItemService.update(cartItem);

        data.put("message", SUCCESS_MESSAGE);
        data.put("subtotal", cartItem.getSubtotal());
        data.put("isLowStock", cartItem.getIsLowStock());
        data.put("quantity", cart.getQuantity());
        return data;
    }

    /**
     * 购物车
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String cart(Model model) {
        model.addAttribute("cart", cartService.getCurrent());
        return "/shop/cart";
    }


    /**
     * 购物车
     */
    @RequestMapping(value = "/checkout", method = RequestMethod.GET)
    public String cartCheckOut(Model model) {
        Member member=memberService.getCurrent();
        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            return "redirect:/shop/cart";
        }
        List<Receiver> receivers=receiverService.getListData("o.member.id=?1", new Object[]{member.getId()});
        if(receivers.size()==0){
            model.addAttribute("redirectUrl","/shop/cart/checkout");
            return "redirect:/member/receiver/add";
        }
        if (!isValid(cart)) {
            return ERROR_VIEW;
        }
        Order order = orderService.build(cart, null, null, null, false, null, false, null);
        model.addAttribute("order", order);
        model.addAttribute("receiver",receivers.get(0));
        model.addAttribute("cartToken", cart.getToken());
        model.addAttribute("member",memberService.getCurrent());
        model.addAttribute("paymentMethods", paymentMethodService.getListData());
        return "/shop/cart-checkout";
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> delete(Long id) {
        Map<String, Object> data = new HashMap<String, Object>();
        Cart cart = cartService.getCurrent();
        if (cart == null || cart.isEmpty()) {
            data.put("message", Message.error("购物车不能为空"));
            return data;
        }
        CartItem cartItem = cartItemService.find(id);
        Set<CartItem> cartItems = cart.getCartItems();
        if (cartItem == null || cartItems == null || !cartItems.contains(cartItem)) {
            data.put("message", Message.error("购物车无该商品"));
            return data;
        }
       // cartItems.remove(cartItem);
        //cartItemService.delete(cartItem);
        cartItemService.delete(id);
        data.put("message", SUCCESS_MESSAGE);
        data.put("quantity", cart.getQuantity());
        data.put("effectivePrice", cart.getPrice());
        data.put("isLowStock", cart.getIsLowStock());
        return data;
    }


    /**
     * 清空
     */
    @ResponseBody
    @RequestMapping(value = "/clear", method = RequestMethod.POST)
    public Message clear() {
        Cart cart = cartService.getCurrent();
        cartService.delete(cart);
        return SUCCESS_MESSAGE;
    }

}
